#include "view.h"
#include "components/buffer.h"
#include <memory>
#include <spdlog/spdlog.h>

View::View(Window* parent, const Rect &rect,
		   std::shared_ptr<Buffer> buffer)
	: _parent(parent), _buffers(), _window_rect(rect){

	// init buffer
	if (!buffer) {
		_buffers.push_back(std::make_shared<Buffer>());
	} else {
		_buffers.push_back(buffer);
	}
	_active_buffer = _buffers.back();

	// init window
	_window = std::shared_ptr<WINDOW>(
		newwin(_window_rect.area.lines, _window_rect.area.cols, _window_rect.pos.y,
			   _window_rect.pos.x),
		delwin);
	assert(_window != nullptr);
}

void View::reset(const Rect &rect) {
	_window_rect = rect;
	
	_window = std::shared_ptr<WINDOW>(
		newwin(_window_rect.area.lines, _window_rect.area.cols, _window_rect.pos.y,
			   _window_rect.pos.x),
		delwin);
}

std::shared_ptr<Buffer> View::get_active_buffer() { return _active_buffer; }

void View::update() {
	WINDOW *window = _window.get();
	assert(window != nullptr);
	auto r = get_window_rect();
	werase(window);
	waddwstr(window, _active_buffer->gap_buffer.GetBuffer());
	box(window, '|', '-');
	wnoutrefresh(window);
}
